import React from 'react'
import Table, { TableProps, ColumnProps } from 'antd/lib/table'

import http from 'services/http'
import { AxiosRequestConfig } from 'axios';
import { getApi } from 'utils/getApi'


type requestFunc = (offset: number) => AxiosRequestConfig
interface IPageTableProps extends TableProps<any> {
	columns: any,
	actionCode?: string,
	request?: string | AxiosRequestConfig | requestFunc,
	defaultOffset?: number,
	limit?: number,
	filter?: object,
}

interface IPageTableState {
	loading: boolean,
	total: number,
	offset: number,
	dataSource: object[]
}
export default class PageTable extends React.Component<IPageTableProps, IPageTableState> {
	static defaultProps = {
		limit: 30,
		defaultOffset: 0,
		filter: {}

	} as IPageTableProps
	constructor(props: IPageTableProps) {
		super(props);
		let dataSource = props.dataSource || [];
		this.state = {
			offset: props.defaultOffset || 0,
			loading: false,
			dataSource,
			total: dataSource.length
		}
	}
	componentDidMount() {
		if (this.state.dataSource!.length > 0)
			return
		this.fetchData();
	}

	componentDidUpdate(preProps: IPageTableProps, prevState: IPageTableState) {
		if (this.props.request !== preProps.request)
			this.fetchData();
	}

	fetchData = async (filter: object = {}) => {
		const { request, actionCode } = this.props;
		if (!request && !actionCode)
			return;

		let finalRequest = {} as AxiosRequestConfig;
		if (actionCode) {
			finalRequest = {
				url: getApi(actionCode),
			}
		} else {
			if (typeof request === 'function') {
				const tempRequest = request(this.state.offset)
				if (typeof tempRequest === 'string')
					finalRequest.url = tempRequest;
				if (typeof tempRequest === 'object')
					finalRequest = { ...tempRequest };
			}
			if (typeof request === 'string') {
				finalRequest.url = request;
			}
			if (typeof request === 'object') {
				finalRequest = { ...request };
			}
		}
		console.log('filter:', filter)
		const defaultParams = {
			offset: this.state.offset,
			limit: this.props.limit,
			filter: this.props.filter
		}
		finalRequest = {
			params: { filter, ...defaultParams, },
			...finalRequest
		} as AxiosRequestConfig

		this.setState({
			loading: true,
		})

		try {
			const resData = await http.post(finalRequest.url as string, finalRequest.params);
			let list = resData.data.entities || [];
			list.forEach((item: any, index: number) => {
				item.key = index + 1;
			})
			//
			this.setState({
				dataSource: list,
				loading: false,
				total: resData.data.next.total,
			})

		} catch (ex) {
			this.setState({ loading: false })
		}
	}

	render() {
		const { dataSource, loading, total } = this.state;
		const props = this.props;
		let { pagination, style } = props
		if (pagination) {
			pagination = Object.assign(pagination, { total })
		}

		return (
			<Table
				{...props}
				loading={loading}
				dataSource={dataSource}
				pagination={pagination}
				style={{ 'backgroundColor': '#f8f8f8', ...style }}
			/>
		)
	}

}
